﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace FrogEngine
{
	public class FpsDisplay : GameEntityBase, ILogical, IRenderable, IHasContent
	{
		SpriteBatch spriteBatch;
		SpriteFont spriteFont;
		GraphicsDevice graphicsDevice;

		int frameRate = 0;
		int frameCounter = 0;
		TimeSpan elapsedTime = TimeSpan.Zero;


		public FpsDisplay(IEngine engine)
			: base(engine)
		{
			this.graphicsDevice = engine.GraphicsDevice;
			this.spriteBatch = engine.SpriteBatch;

			this.Services.Add(engine.GetService<UpdateEntityService>());
			this.Services.Add(engine.GetService<RenderService>());
			this.Services.Add(engine.GetService<GameContentService>());

			foreach (var service in this.Services)
				service.Subscribe(this);
		}

		public void Update(GameTime gameTime)
		{
			elapsedTime += gameTime.ElapsedGameTime;

			if (elapsedTime > TimeSpan.FromSeconds(1))
			{
				elapsedTime -= TimeSpan.FromSeconds(1);
				frameRate = frameCounter;
				frameCounter = 0;
			}
		}

		public void Render(GameTime gameTime)
		{
			frameCounter++;

			string fps = string.Format("fps: {0}", frameRate);

			spriteBatch.Begin();

			spriteBatch.DrawString(spriteFont, fps, new Vector2(33, 33), Color.Black);
			spriteBatch.DrawString(spriteFont, fps, new Vector2(32, 32), Color.White);

			spriteBatch.End();
		}

		public ContentManager ContentManager { get; set; }

		public IEnumerable<string> AssetNames()
		{
			return new List<string> { "font" };
		}

		public void LoadContent()
		{
			spriteFont = ContentManager.Load<SpriteFont>("font");
		}
	}
}
